package test.threadlocal;

import java.util.Random;

public class ThreadLocalTest2
{

	private ThreadLocal tl = new ThreadLocal();
	public String s = null;

	public void setV(Object v)
	{
		tl.set(v);
	}

	public Object getV()
	{
		return tl.get();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		ThreadLocalTest2 m = new ThreadLocalTest2();
		Thread1 t1 = new Thread1(m);
		Thread1 t2 = new Thread1(m);
		Thread1 t3 = new Thread1(m);
		Thread1 t4 = new Thread1(m);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

class Thread1 extends Thread
{
	private ThreadLocalTest2 m = null;

	public Thread1(ThreadLocalTest2 mm)
	{
		m = mm;
	}

	public void run()
	{
		if(m.getV()==null){
			m.setV(new Random().nextFloat());
		}
		System.err.println(Thread.currentThread().getId() + ": " + m.getV());
		m.s = "TID" + Thread.currentThread().getId();
//		m.setV(Thread.currentThread().getId());	//will 覆盖原先的set
		try
		{
			Thread.sleep(1000);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getId() + ": " + m.getV() +",common variable "+ m.s);
	}
}
